package com.renjian.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

import com.renjian.model.KeyMap;

public abstract class HttpConnectionUtil implements Constant {

	public HttpConnection c = null;
	public InputStream is = null;
	public OutputStream os = null;

	public KeyMap[] impreterXml(String xml) {
		return null;
	}

	public boolean processRequest(String url, KeyMap[] parameters,
			KeyMap[] keyMap) throws IOException {
		logger.log("url:" + url);
		if (hack.isWifiEnabled)
			url = url + ";interface=wifi";
		c = (HttpConnection) Connector.open(url);

		setCommonParameters();
		setExtrasParameters(keyMap);
		if (processReq(parameters) && processResults())
			return true;
		return false;
	}

	public void setExtrasParameters(KeyMap[] keyMap) throws IOException {
		for (int i = 0; i < keyMap.length; i++) {
			logger.log("key:" + keyMap[i].getKey());
			logger.log("val:" + keyMap[i].getVal());
			c.setRequestProperty(keyMap[i].getKey(), keyMap[i].getVal());
		}
	}

	private boolean processResults() throws IOException {
		// Get the ContentType
		String type = c.getType();
		processType(type);

		// Get the length and process the data
		int len = (int) c.getLength();

		logger.log("len is : " + len);

		if (len > 0) {
			int actual = 0;
			int bytesread = 0;
			byte[] data = new byte[len];
			while ((bytesread != len) && (actual != -1)) {
				actual = is.read(data, bytesread, len - bytesread);
				bytesread += actual;
			}
			return process(data);
		} else {
			int ch;
			int cnt = 0;
			while ((ch = is.read()) != -1) {
				// process((byte) ch);
				ret[cnt] = (byte) ch;
				cnt++;
			}
			return process(ret);
		}
	}

	public byte[] ret = new byte[1024];

	// public abstract void process(byte ch) ;

	public abstract boolean process(byte ch[]);

	public void processType(String type) {
		logger.log("type is:" + type);
	}

	private String wrapURI(KeyMap[] keyMap) throws IOException {
		String tmp = "";
		// if (keyMap.length != 0)
		// tmp += "?"; // "%3F";
		for (int i = 0; i < keyMap.length; i++) {
			// c.setRequestProperty("Authorization", base64_credentials);
			tmp += keyMap[i].getKey() + "=" + keyMap[i].getVal();
			if (i == (keyMap.length - 1))
				continue;
			tmp += "&";// "&";
		}

		logger.log("tmp:" + tmp);
		return tmp;
	}

	private boolean processReq(KeyMap[] parameters) throws IOException {
		int rc;
		// Getting the output stream may flush the headers
		os = c.openOutputStream();
		// start
		String str = wrapURI(parameters);
		if (hack.cookie != null && !"".equals(hack.cookie)) {
			logger.log("set cookie to request:" + hack.cookie);
			c.setRequestProperty("Cookie", hack.cookie);
			str += "&"+hack.cookie;
		}
		logger.log("post data;" + str);
		byte postmsg[] = str.getBytes("utf-8");
		for (int i = 0; i < postmsg.length; i++) {
			os.write(postmsg[i]);
		}
		os.flush();
		// end
		// Getting the response code will open the connection,
		// send the request, and read the HTTP response headers.
		// The headers are stored until requested.
		rc = c.getResponseCode();
		// String cookie = "";
		// if(hack.cookie == null && "".equals(hack.cookie))
		if ((hack.cookie == null || "".equals(hack.cookie))
				&& !hack.isCheckWifi) {
			String cookie = c.getHeaderField("Set-Cookie");
			//hack.cookie = cookie;
			logger.log("set cookie to app:" + cookie);
			if (cookie != null) {
				int start = 0;
				int end = cookie.indexOf(";");
				String tmp = cookie.substring(start, end);
				logger.log("cookie:" + tmp);
				hack.cookie = tmp;
			}
		}
		logger.log("i got the response code rc is :" + rc);

		/*
		 * if (rc != HttpConnection.HTTP_OK) { logger.log("HTTP response code: " +
		 * rc); return false; }
		 */
		is = c.openInputStream();
		logger.log("input is open .");
		return true;
	}

	private void setCommonParameters() throws IOException {
		c.setRequestMethod(HttpConnection.POST);
		// c.setRequestProperty("If-Modified-Since", "29 Oct 1999 19:43:31
		// GMT");
		c.setRequestProperty("Content-Type", "application/xml; charset=utf-8");
		// c.setRequestProperty("Accept-Encoding", "gzip");
		// c.setRequestProperty("User-Agent", "MyUserAgentHere");
		// c.setRequestProperty("Content-Language", "en-US");
		// c.setRequestProperty("Cache-Control",
		// "no-store, no-cache, must-revalidate");
		if (hack.cookie != null && !"".equals(hack.cookie)) {
			logger.log("set cookie to request:" + hack.cookie);
			c.setRequestProperty("Cookie", hack.cookie);
		}
	}
}
